/*  This file is part of Basepairs, an application for calculations on
    DNA Sequence polymorphism.
    Copyright (C) 2013 Kim Lindgren

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.*/


package basepairs;

import java.util.ArrayList;

public class NucleotideDiversity {
    NucleotideDiversity() {
    
    }
    
    public double PI;
    public double pi;
    
    public double calcAvgPairwiseDiff(){
        int nrSequences = Sequences.selected.size();
        int currSequence = 0;
        int sSequence;
        double diffs;
        double total;
        
        String s1;
        String s2;
        
        ArrayList<Double> differences = new ArrayList<Double>();
        
        while(currSequence < nrSequences){
            sSequence = 0;
            diffs = 0;
                        
            s1 = Sequences.selected.get(currSequence);
            
            while(sSequence < nrSequences){
                if(sSequence != currSequence){
                    s2 = Sequences.selected.get(sSequence);
                    
                    for(int pos = 0; pos < Sequences.sequenceLength; pos++){                       
                        if(!Sequences.gaps.contains(pos)){
                            if(!s1.substring(pos,pos+1).equals(s2.substring(pos,pos+1))){
                                diffs++;
                            }
                        }
                    }
                }
                
                sSequence++;
            }
            
            differences.add(diffs/Sequences.selected.size());
            currSequence++;
        }
        
        total = Utility.sumList(differences);
        this.PI = total/(double)(differences.size()-1);
        this.pi = this.PI/(double)(Sequences.sequenceLength-Sequences.gaps.size());
        
        return this.pi;
    }
}
